package com.cunfang.interceptor;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

public class MyException implements HandlerExceptionResolver {

	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
			Object object,Exception e) {
		ModelAndView model = new ModelAndView();
		model.setViewName("404");
		try {
		Map<String,String> result = new HashMap();
		for (StackTraceElement s : e.getStackTrace()) {				
			  String line = null;
			  	Class<?> c3 = Class.forName(s.getClassName());
			  	String className = c3.getName();
			  	String[] name =className.split("\\.");
			  	className=name[name.length-1]+".java";
	    	    int n = s.getLineNumber()-2;
	    	    String file="src";
	    	    for(String value:name){
	    	    	file=file+"\\"+value;
	    	    }
	    	    BufferedReader br = new BufferedReader(new FileReader(file+".java"));
	    	    int i=0;
	    	    while(n-->1){
	    	    	br.readLine();
	    	    }
	    	    String bodys="";
	    	    bodys="类名：" + name[name.length-1]+"  第 "+s.getLineNumber()+
	    	    		" 行    方法名:"+s.getMethodName()+"  错误类型:"+e.getClass().getName()+"\n";		    	   
	    	    while ((line = br.readLine()) != null  && i<5) {
	    	    	bodys=bodys+(s.getLineNumber()-2+i)+".  "+line+"\n";
	    	        i++;
	    	    }
	    	    result.put("bodys"+i, bodys);
	    	    br.close();

		}
		List<String> value =new ArrayList<String>();
		for(String v: result.values()){
			value.add(v);
		}
		model.addObject("result", value);
		} catch (Exception ee) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return model;
	}
}
	
	



